package com.marktotop.controller;


import com.marktotop.pojo.User;
import com.marktotop.service.IGoodsService;
import com.marktotop.vo.GoodsVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Date;

/**
 * GoodController
 *
 * @author WXLD
 * @Data 2021/6/18
 * @Since 1.0
 */
@Controller
@RequestMapping("/goods")
public class GoodsController {

    @Autowired
    private IGoodsService goodsService;

    /**
     * 验证是否登录，跳转至商品列表
     *
     * @param model
     * @return
     */
    @RequestMapping("/toList")
    public String toList(Model model, User user){
        model.addAttribute("user",user);
        model.addAttribute("goodsList",goodsService.findGoodsVoList());
        return "goodsList";
    }

    /**
     * 跳转至商品详情页面
     *
     * @param model
     * @param user
     * @param goodsId
     * @return
     */
    @RequestMapping("/toDetail/{goodsId}")
    public String toDetail(Model model, User user, @PathVariable Long goodsId){
        model.addAttribute("user",user);
        GoodsVO goodsVO = goodsService.findDetailByGoodsId(goodsId);
        Date startTime = goodsVO.getStartTime();
        Date endTime = goodsVO.getEndTime();
        Date currentTime = new Date();
        // 秒杀状态
        int secKillStatus = 0;
        // 秒杀倒计时
        int remainSeconds = 0;
        if(currentTime.before(startTime)){
            // 未开始
            remainSeconds = ((int) (startTime.getTime() - currentTime.getTime())/1000);
        }else if (currentTime.after(endTime)){
            // 已结束
            secKillStatus = 2;
            remainSeconds = -1;
        } else {
            // 正在进行
            secKillStatus = 1;
            remainSeconds = 0;
        }
        model.addAttribute("goods",goodsVO);
        model.addAttribute("secKillStatus",secKillStatus);
        model.addAttribute("remainSeconds",remainSeconds);
        return "goodsDetail";
    }
}
